
pred_plm<-function(model, inc_covs,covs,time_efs){


fx<-fixef(model) 


dt<-data.frame(names(fx), as.vector(fx))

names(dt)<-c("ccode","fx")


if(inc_covs==F){
  
  covs_full<-c("ccode","year","D","Y")
  
  
}


if(inc_covs!=F){
  
covs_full<-c("ccode","year","D","Y",covs)

} 


dt1<-dat[, covs_full]

dt2<-merge(dt1,dt,by="ccode")

dt2<-pdata.frame(dt2,index=c("ccode","year"))


if(time_efs==T){
  
  
  time<-fixef(model,effect="time")
  
  time<-data.frame(as.vector(time),names(time))
  
  names(time)<-c("time_fx","year")
  
  dt2<-merge(dt2,time,by="year")
  
  dt2<-pdata.frame(dt2,index=c("ccode","year"))
  
}





if(inc_covs==F){
  
  dt2$pred<-cbind(log(lag(dt2$Y) ) ) %*% coef(model) +dt2$fx
  
}



if(inc_covs!=F){
  
  dt2$pred<-as.matrix(cbind(log(lag(dt2$Y) ) ,dt2[,covs])) %*% coef(model) +dt2$fx
  
}


if(time_efs==T){
  
  
  dt2$pred<-dt2$pred+dt2$time_fx
  
}



dt2$round_pred<-round(dt2$pred)




dt2$correct<- dt2$round_pred==dt2$D 

correct_pred<-sum(dt2$correct,na.rm=T)/nrow(dt2[!is.na(dt2$pred) | !is.na(dt2$round_pred), ])

dt2$trans<-abs(diff(dt2$D))
dt2$trans_pred<-abs(diff(dt2$round_pred))

trans<-dt2[dt2$trans==1,]


trans<-trans[order(trans$ccode),]
trans<-trans[!is.na(trans$ccode),]


dt2$year<-as.numeric(as.character(dt2$year))
trans$year<-as.numeric(as.character(trans$year))

trans$trans_pred5<-NA

for(i in 1:nrow(trans)){
  
  sub<-dt2[dt2$ccode==trans[i,]$ccode & ( dt2$year <= trans[i,]$year +2 & dt2$year >= trans[i,]$year -2   )  ,]
  
  
  trans[i,]$trans_pred5<-ifelse(sum(sub$trans_pred,na.rm=T) >= 1, 1,0)
  
}


correct_trans1<-sum(trans$trans_pred,na.rm=T)/sum(trans$trans,na.rm=T)

correct_trans5<-sum(trans$trans_pred5,na.rm=T)/sum(trans$trans,na.rm=T)


data.frame(correct_pred,correct_trans1,correct_trans5)


}
